﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessHandler;
using EasyCode.Utility;
using BusinessHanler;
public partial class Page_AddNews : System.Web.UI.Page
{
    private New newsItem;
    private NewsController newsController;
    private CategoryController categoryController;
    private NewsPositionController newsPositionController;
    private NewsDataClassesDataContext datacontext;
    private MovieStyleController movieStyleController;
    private string imgFolder=System.Configuration.ConfigurationManager.AppSettings["NEWS_IMG_FOLDER"];
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session["ImagePath"]=imgFolder;
            this.GetCategory();
            this.GetNewsPosition();
            this.GetMovieStyle();
            this.LoadValueForUpdate();
        }
    }

    #region Init Value
    private void InnitValue()
    {
        newsItem.NewsTitle=HttpUtility.HtmlEncode(this.TextBox_NewsTitle.Text.Trim());
        newsItem.NewsDescription=HttpUtility.HtmlEncode(this.TextBox_Description.Text.Trim());
        newsItem.NewsDetail=HttpUtility.HtmlEncode(this.TextBox_Details.Text.Trim());
        newsItem.CreatedDate=DateTime.Now;
        newsItem.LastModifiedDate=DateTime.Now;
        newsItem.SubPageLastModify=DateTime.Now;
        newsItem.PublishDate=Protector.DateTime(this.TextBox_PublishDate.Text, DateTime.Now);
        newsItem.Status=this.CheckBox_IsAcitve.Checked;
        newsItem.ShowHomePage=this.CheckBox_ShowOnHomePage.Checked;
        newsItem.NewsTotalView=0;
    }
    private void GetCategory()
    {
        categoryController=CategoryController.Instance;
        Dictionary<int, string> myDic=new Dictionary<int, string>();
        int iCount=0;
        Dictionary<int, string> objListCat=BuilTreeList(ref myDic, ref iCount, categoryController.GetCategoryforInsertNews());
        this.DropDownList_Category.DataSource=objListCat;
        this.DropDownList_Category.DataTextField="Value";
        this.DropDownList_Category.DataValueField="Key";
        this.DropDownList_Category.DataBind();
        this.DropDownList_Category.Items.Insert(0, new ListItem("--Select category--", "0"));
    }
    private void GetNewsPosition()
    {
        newsPositionController=NewsPositionController.Instance;
        this.DropDownList_HomePagePosition.DataSource=newsPositionController.GetNewsPositionList();
        this.DropDownList_HomePagePosition.DataTextField="PositionName";
        this.DropDownList_HomePagePosition.DataValueField="PositionType";
        this.DropDownList_HomePagePosition.DataBind();
        this.DropDownList_HomePagePosition.Items.Insert(0, new ListItem("--Select home page position--", "-1"));
        this.DropDownList_SubPagePosition.DataSource=newsPositionController.GetNewsPositionList();
        this.DropDownList_SubPagePosition.DataTextField="PositionName";
        this.DropDownList_SubPagePosition.DataValueField="PositionType";
        this.DropDownList_SubPagePosition.DataBind();
        this.DropDownList_SubPagePosition.Items.Insert(0, new ListItem("--Select sub page position--", "-1"));
    }
    private void GetMovieStyle()
    {
        movieStyleController=MovieStyleController.Instance;
        this.DropDownList_MovieStyle.DataSource=movieStyleController.GetStyleList();
        this.DropDownList_MovieStyle.DataTextField="MovieTypeName";
        this.DropDownList_MovieStyle.DataValueField="MovieTypeId";
        this.DropDownList_MovieStyle.DataBind();
        this.DropDownList_MovieStyle.Items.Insert(0, new ListItem("--Select movie style--", "0"));
    }
    #endregion
    protected Dictionary<int, string> BuilTreeList(ref Dictionary<int, string> myDic, ref int iCount, List<Category> myList)
    {
        this.categoryController=CategoryController.Instance;
        List<Category> allChild=categoryController.GetAllChildCat();
        foreach (Category item in myList)
        {
            int addKey=Protector.Int(item.CategoryID);
            string addValue=GetStringName(0)+HttpUtility.HtmlDecode(item.CategoryName);
            myDic.Add(addKey, addValue);

            List<Category> objListChild=(from o in allChild
                                         where o.CategoryParentID==addKey
                                         select o).ToList();
            if (objListChild.Count>0)
            {
                iCount++;
                BuilTreeListChild(allChild, addKey, ref myDic, ref iCount);
                iCount--;
            }
        }
        if (myDic!=null&&myList.Count>0)
        {
            return myDic;
        }
        else
        {
            return new Dictionary<int, string>();
        }
    }
    protected void BuilTreeListChild(List<Category> myListOriginal, int parentID, ref Dictionary<int, string> myDic, ref int iCount)
    {
        List<Category> myList=(from o in myListOriginal
                               where o.CategoryParentID==parentID
                               select o).ToList();

        if (myList!=null)
        {
            foreach (Category item in myList)
            {
                int addKey=Protector.Int(item.CategoryID);
                string addValue=GetStringName(iCount)+HttpUtility.HtmlDecode(item.CategoryName);
                myDic.Add(addKey, addValue);
                List<Category> objListChild=(from o in myListOriginal
                                             where o.CategoryID==addKey
                                             select o).ToList();
                if (objListChild.Count>0)
                {
                    iCount++;
                    BuilTreeListChild(myListOriginal, addKey, ref myDic, ref iCount);
                    iCount--;
                }
            }
        }
    }
    protected string GetStringName(int levelID)
    {
        string abc="";
        for (int o=0; o<levelID; o++)
        {
            abc+="|-- ";
        }
        return abc;
    }

    protected void Button_Save_Click(object sender, EventArgs e)
    {
        if (this.Button_Save.Text.Trim().ToUpper()=="SAVE")
        {
            if (!CheckRoles.CanInsert())
            {
                Response.Redirect(ResolveUrl("~/Page/AccessDeny.aspx"));
            }
            this.newsItem=new New();
        }
        else
        {
            if (!CheckRoles.CanEdit())
            {
                Response.Redirect(ResolveUrl("~/Page/AccessDeny.aspx"));
            }
            if (Session["firstid"]==null)
            {
                Response.Redirect("NewsManagement.aspx");
            }
            datacontext=new NewsDataClassesDataContext();
            this.newsItem=(from o in datacontext.News
                           where o.NewsID==Protector.Int(Session["firstid"])
                           select o).SingleOrDefault();
            if (this.newsItem==null)
            {
                Response.Redirect("NewsManagement.aspx");
            }
        }
        this.InnitValue();
        if (this.DropDownList_Category.SelectedIndex==0||this.DropDownList_Category.Items.Count<1)
        {
            this.Message_Alert.SetError(Resources.News.ConfirmSelectCategory);
            return;
        }
        if (this.TextBox_External.Text.Trim()!=string.Empty)
        {
            if (this.DropDownList_MovieStyle.SelectedIndex<1)
            {
                this.Message_Alert.SetError(Resources.News.SelectMovieStyle);
                return;
            }
            newsItem.ExternalLink=HttpUtility.HtmlEncode(this.TextBox_External.Text);
            newsItem.MovieTypeID=Protector.Int(this.DropDownList_MovieStyle.SelectedValue);
        }
        newsItem.NewsCategoryID=Protector.Int(this.DropDownList_Category.SelectedValue, true);
        if (this.CheckBox_ShowOnHomePage.Checked)
        {
            if (this.DropDownList_HomePagePosition.SelectedIndex == 0 || this.DropDownList_HomePagePosition.Items.Count < 1)
            {
                this.Message_Alert.SetError(Resources.News.ConfirmSelectDisplayPosition);
                return;
            }
            if (this.Button_Save.Text.Trim().ToUpper() == Resources.News.Update.ToUpper())
            {
                if (Protector.Bool(Session["homestatus"], false) == false)
                {
                    this.newsItem.LastModifiedDate = DateTime.Now;
                    this.newsItem.NewsHomePagePositionID = Protector.Int(this.DropDownList_HomePagePosition.SelectedValue);
                }
                else
                {
                    if (Protector.Int(Session["homeposition"], 0) != Protector.Int(this.DropDownList_HomePagePosition.SelectedValue, 0))
                    {
                        Session["homeposition"] = this.DropDownList_HomePagePosition.SelectedValue;
                        this.newsItem.NewsHomePagePositionID = Protector.Int(this.DropDownList_HomePagePosition.SelectedValue);
                        this.newsItem.LastModifiedDate = DateTime.Now;
                    }
                }
            }
            else
            {
                this.newsItem.LastModifiedDate = DateTime.Now;
                this.newsItem.NewsHomePagePositionID = Protector.Int(this.DropDownList_HomePagePosition.SelectedValue);
            }
            newsItem.NewsCatParentID = this.GetParentID(Protector.Int(this.DropDownList_Category.SelectedValue));
            if (newsItem.NewsCatParentID.HasValue && newsItem.NewsCatParentID.ToString() == this.DropDownList_Category.SelectedValue.ToString())
            {
                newsItem.NewsCatParentID = null;
            }

        }
        else
        {
            newsItem.NewsCatParentID = null;
        }
        if (this.DropDownList_SubPagePosition.SelectedIndex==0||this.DropDownList_SubPagePosition.Items.Count<1)
        {
            this.Message_Alert.SetError(Resources.News.ConfirmSelectSubPosition);
            return;
        }
        else
        {
            if (this.Button_Save.Text.Trim().ToUpper()==Resources.News.Update.ToUpper())
            {
                if (this.newsItem.SubPagePositionID.HasValue&&this.newsItem.SubPagePositionID.Value.ToString()!=this.DropDownList_SubPagePosition.SelectedValue.ToString())
                {
                    this.newsItem.SubPageLastModify=DateTime.Now;
                    this.newsItem.SubPagePositionID=Protector.Int(this.DropDownList_SubPagePosition.SelectedValue.ToString());
                }
                else if (!this.newsItem.SubPagePositionID.HasValue)
                {
                    this.newsItem.SubPageLastModify=DateTime.Now;
                    this.newsItem.SubPagePositionID=Protector.Int(this.DropDownList_SubPagePosition.SelectedValue.ToString());
                }
            }
            else
            {
                this.newsItem.SubPageLastModify=DateTime.Now;
                this.newsItem.SubPagePositionID=Protector.Int(this.DropDownList_SubPagePosition.SelectedValue.ToString());
            }
        }
        if (this.TextBox_Details.Text.Trim()==string.Empty)
        {
            this.Message_Alert.SetError(Resources.News.ConfirmInputNewsDetail);
            return;
        }
        DateTime publishDate;
        if (!DateTime.TryParse(this.TextBox_PublishDate.Text, out publishDate))
        {
            this.Message_Alert.SetError(Resources.News.EnterPublishDate);
            return;
        }
        string avatarFilePath=string.Empty;
        string sliderFilePath=string.Empty;
        string error=string.Empty;
        if (this.FileUpload_Avartar.HasFile)
        {
            if (Commons.Upload(this.FileUpload_Avartar, imgFolder, new string[] { ".png", ".jpg", ".jpeg" }, ref avatarFilePath, ref error))
            {
            }
            else
            {
                this.Message_Alert.SetError(Resources.News.UploadImageError+" "+error);
                return;
            }
        }
        if (this.FileUpload_Slider.HasFile)
        {
            if (Commons.Upload(this.FileUpload_Slider, imgFolder, new string[] { ".png", ".jpg", ".jpeg" }, ref sliderFilePath, ref error))
            {
            }
            else
            {
                this.Message_Alert.SetError(Resources.News.UploadImageError+" "+error);
                return;
            }
        }
        this.newsItem.PublishDate=publishDate;
        if (!string.IsNullOrEmpty(avatarFilePath))
        {
            this.newsItem.AvatarImage=avatarFilePath;
        }
        if (!string.IsNullOrEmpty(sliderFilePath))
        {
            this.newsItem.SliderPath=sliderFilePath;
        }
        if (this.Button_Save.Text.Trim().ToUpper()==Resources.News.Save.ToUpper())
        {
            try
            {
                newsController=NewsController.Instance;
                newsController.News.InsertOnSubmit(newsItem);
                newsController.SubmitChanges();
                this.Message_Alert.SetSuccess(string.Format(Resources.News.SaveOk, this.TextBox_NewsTitle.Text));
                this.ResetValue();
            }
            catch (Exception ex)
            {
                this.Message_Alert.SetError(string.Format(Resources.News.SaveFail, this.TextBox_NewsTitle.Text)+" Error: "+ex.Message);
            }
        }
        else
        {
            try
            {
                datacontext.SubmitChanges();
                this.Message_Alert.SetSuccess(Resources.News.NewsUpdated);
            }
            catch
            {
                this.Message_Alert.SetError(Resources.News.UpdateFail);
            }
        }
    }
    private void ResetValue()
    {
        this.DropDownList_Category.SelectedIndex=0;
        this.DropDownList_HomePagePosition.SelectedIndex=0;
        this.DropDownList_SubPagePosition.SelectedIndex=0;
        this.TextBox_Description.Text=string.Empty;
        this.TextBox_NewsTitle.Text=string.Empty;
        this.TextBox_PublishDate.Text=string.Empty;
        this.TextBox_Details.Text=string.Empty;
        this.CheckBox_ShowOnHomePage.Checked=false;
        this.TextBox_External.Text=string.Empty;
        this.DropDownList_MovieStyle.SelectedIndex=0;
    }
    private void LoadValueForUpdate()
    {
        int id=Protector.Int(Request.QueryString["id"], 0);
        if (id>0)
        {
            newsController=NewsController.Instance;
            New item=newsController.GetNewsById(id);
            if (item==null)
            {
                Response.Redirect("NewsManagement.aspx");
            }
            this.TextBox_NewsTitle.Text=HttpUtility.HtmlDecode(item.NewsTitle);
            this.TextBox_Description.Text=HttpUtility.HtmlDecode(item.NewsDescription);
            this.TextBox_Details.Text=HttpUtility.HtmlDecode(item.NewsDetail);
            if (item.ShowHomePage.HasValue&&item.ShowHomePage.Value==true)
            {
                this.CheckBox_ShowOnHomePage.Checked=true;
                this.DropDownList_HomePagePosition.SelectedValue=item.NewsHomePagePositionID.ToString();
            }
            this.DropDownList_SubPagePosition.SelectedValue=item.SubPagePositionID.ToString();
            this.DropDownList_Category.SelectedValue=item.NewsCategoryID.ToString();
            if (item.ExternalLink!=string.Empty&&item.MovieTypeID!=null)
            {
                this.DropDownList_MovieStyle.SelectedValue=item.MovieTypeID.Value.ToString();
            }
            this.TextBox_PublishDate.Text=item.PublishDate.Value.ToShortDateString();
            this.Button_Save.Text=Resources.News.Update;
            Session["firstid"]=id;
            Session["homeposition"]=item.NewsHomePagePositionID;
            Session["homestatus"]=item.ShowHomePage;
        }
    }
    List<Category> catList=null;
    private int? GetParentID(int childID)
    {
        categoryController=CategoryController.Instance;
        catList=categoryController.GetAllCat();
        if (catList==null)
        {
            return null;
        }
        return GetRoot(childID);

    }
    private int? GetRoot(int? child)
    {
        foreach (Category item in catList)
        {
            if (item.CategoryID==child&&item.CategoryParentID==null)
            {
                return item.CategoryID;
            }
            else if (item.CategoryID==child)
            {
                return GetRoot(item.CategoryParentID);
            }
        }
        return null;
    }
}